(add-to-load-path (dirname (dirname (current-filename))))
(use-modules (basket))

(define (triangles x y z n)
  (if (= n 0)
    `((,x ,y ,z))
    ((lambda (ts)
       (append (triangles (caar ts) (cadar ts) (caddar ts) (1- n))
               (triangles (cadr ts) (caddr ts) (cadddr ts) (1- n))))
     (list-ref
       `(((,x ,y ,(vec-midpoint x z)) . (,y ,z ,(vec-midpoint x z)))
         ((,y ,z ,(vec-midpoint x y)) . (,x ,z ,(vec-midpoint x y)))
         ((,z ,x ,(vec-midpoint y z)) . (,x ,y ,(vec-midpoint y z))))
       (random 3)))))

(define filled-triangles
  (append (triangles '(0 . 0) '(0 . 1) '(1 . 0) 8)
          (triangles '(1 . 1) '(0 . 1) '(1 . 0) 8)))

(define image
  (map (lambda (x)
         `(set (color ,(hsv->rgb `(,(caar x) 1 1)))
               (fill ,x)))
       filled-triangles))

(render-cairo-png image 1024 (cadr (program-arguments)))
